package cn.jbit.menutree;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author 张在成
 */
public class TestMenu {

    @Test
    public  void  menuTest() throws IOException, ClassNotFoundException, SQLException {

        Properties p=new Properties();

        InputStream stream = TestMenu.class.getClassLoader().getResourceAsStream("database.properties");

        p.load(stream);

        String user = p.getProperty("user");

        String password=p.getProperty("password");

        String diverClass=p.getProperty("diverClass");

        String  url=p.getProperty("url");
        //获取链接

        Class.forName(diverClass);

        Connection connection = DriverManager.getConnection(url,user,password);

        //查询数据数据
        PreparedStatement statement = connection.prepareStatement("select  * from menu");

        ResultSet resultSet = statement.executeQuery();

        List<Menu> list=new ArrayList<>();

        while (resultSet.next()){
            int id = resultSet.getInt(1) ;
            String name = resultSet.getString(2) ;
            int age = resultSet.getInt(3) ;
            String parnet_id = resultSet.getString(4);
            String or_id = resultSet.getString(5);

            Menu menu=new Menu();
            menu.setId(id);
            menu.setName(name);
            menu.setAge(age);
            menu.setParent_id(parnet_id);
            menu.setOr_id(or_id);

            list.add(menu);
        }

        //System.out.println(Arrays.asList(list));

        List<Menu> menuInfo = getListMenuInfo(list);

        System.out.println(menuInfo);


    }


    /**
     * 写递归方法
     * @return
     */
    public List<Menu> getListMenuInfo(List<Menu> list){
        //存放集合信息
        List<Menu> menuList=new ArrayList<>();

        for (Menu menu:list) {
            if ("0".equals(menu.getParent_id())) {
                getListMenu(menu, list);
                menuList.add(menu);
            }
        }

        return  menuList;
    }

    /**
     * 递归获取下级菜单
     */
    public  void  getListMenu(Menu root,List<Menu> menuList){

        List<Menu> childList=new ArrayList<>();

        for (Menu menu:menuList){
            if (root.getOr_id().equals(menu.getParent_id())){
                childList.add(menu);
            }
        }
        if (childList.size()==0){
            return ;
        }
        //设置孩子节点
        root.setChildren(childList);

        //遍历获取子菜单的子菜单
        for (Menu menu:childList){
            getListMenu(menu,menuList);
        }
    }
}
